package com.shy.base.controller;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.shy.base.shiro.ShiroUser;

/**
 * <p>Title:BaseController </p>
 * <p>Description:controller父类 </p>
 * <p>Company:ipebg </p> 
 * @author H2013788
 * @date 2018/6/9
 */
public abstract class BaseController {
    
	/**
     * log
     */
	private Logger logger = LogManager.getLogger(this.getClass());
    
    @Autowired
	protected HttpServletRequest request;
    
    @Autowired
	protected HttpServletResponse response;
    
	protected HttpSession session;

	protected HttpServletRequest getRequest() {
		return this.request;
	}

	protected HttpServletResponse getResponse() {
		return this.response;
	}

	protected HttpSession getSession() {
		return this.session;
	}

	/**
	 * form表单提交 Date类型数据绑定
	 * 
	 * @param binder
	 * @see [类、类#方法、类#成员]
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateWebBindingInitializer init = new DateWebBindingInitializer();
		init.initBinder(binder);
	}

	/**
     * 说明：ModelAttribute的作用 
     * 1)放置在方法的形参上：表示引用Model中的数据
     * 2)放置在方法上面：表示请求该类的每个Action前都会首先执行它，也可以将一些准备数据的操作放置在该方法里面。
     * 3)modelAttribute适用于全局公共信息的设置，非线程安全，此处request response不建议如此使用
     */
	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request,
			HttpServletResponse response) {
		//this.request = request;
		//this.session = request.getSession();
		//this.response = response;
	}
	
    /**
     * 获取当前登录用户对象
     * @return {ShiroUser}
     */
    public ShiroUser getShiroUser() {
        return (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * 获取当前登录用户id
     * @return {Long}
     */
    public Integer getUserId() {
        return this.getShiroUser().getId();
    }

    /**
     * 获取当前登录用户名
     * @return {String}
     */
    public String getStaffName() {
        return this.getShiroUser().getName();
    }

	// /////////// 文件上传 begin///////////////////

	/**
	 * 上传文件并以UUID重命名
	 * 
	 * @param fileDoc
	 *            源文件
	 * @param fileDir
	 *            上传路径
	 * @return String newFileName 新文件名
	 */
	public String upLoadFile(MultipartFile fileDoc, String fileDir) {
		if (null != fileDoc) {
			isExists(fileDir);
			String fileTypeName = fileDoc.getOriginalFilename().substring(
					fileDoc.getOriginalFilename().lastIndexOf(".") + 1);
			String newFileName = UUID.randomUUID().toString() + "."
					+ fileTypeName;
			File targetFile = new File(fileDir, newFileName + "");
			try {
				fileDoc.transferTo(targetFile);
				return newFileName;
			} catch (Exception e) {
				e.printStackTrace();
				writePrintStackTrace(e);
			}
		}
		return "";
	}

	/**
	 * 上传文件，并保持原名
	 * 
	 * @param fileDoc
	 *            源文件
	 * @param fileDir
	 *            上传路径
	 * @return String fileName 文件名
	 */
	public String upLoadFileKeepOrginalName(MultipartFile fileDoc,
			String fileDir) {
		if (null != fileDoc) {
			isExists(fileDir);
			String fileName = fileDoc.getOriginalFilename();
			File targetFile = new File(fileDir, fileName + "");
			try {
				fileDoc.transferTo(targetFile);
				return fileName;
			} catch (Exception e) {
				e.printStackTrace();
				writePrintStackTrace(e);
			}
		}
		return "";
	}

	/**
	 * 判断文件夹是否存在 不存在则创建一个
	 * 
	 * @param path
	 */
	private void isExists(String path) {
		File file = new File(path);
		if (!file.exists()) {
			File f = new File(file.getPath());
			f.mkdirs();
		}
	}


	/**
	 * 输出异常堆栈信息到日志文件
	 */
	protected void writePrintStackTrace(Exception e) {
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		logger.error(stringWriter.toString());
	}

}
